<template>
  <view class="container">
    <!-- 表单容器 -->
    <view class="form-container">
      <uni-forms ref="form" :model="formData" validateTrigger="bind">
        <!-- 分类 ID 输入项 -->
        <uni-forms-item name="data_id" label="ID" required>
          <uni-easyinput placeholder="请输入分类 ID" v-model="formData.data_id" trim="both"></uni-easyinput>
        </uni-forms-item>
        <!-- 分类名称输入项 -->
        <uni-forms-item name="name" label="名称" required>
          <uni-easyinput placeholder="请输入分类名称" v-model="formData.name" trim="both"></uni-easyinput>
        </uni-forms-item>
        <!-- 分类类型选择项 -->
        <uni-forms-item name="type" label="类型" required>
          <uni-data-picker
            :localdata="categoryTypes"
            v-model="formData.type"
          />
        </uni-forms-item>
        <!-- 排序输入项 -->
        <uni-forms-item name="sort" label="排序">
          <uni-easyinput placeholder="类别显示顺序" type="number" v-model="formData.sort"></uni-easyinput>
        </uni-forms-item>
        <!-- 按钮组 -->
        <view class="button-group">
          <button type="primary" class="button" @click="submit">提交</button>
          <button class="button" @click="cancel">取消</button>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script>
import { validator } from '@/uni_modules/uni-cms/common/validator/uni-cms-categories.js';

const db = uniCloud.database();
const dbCollectionName = 'jl_product_categories';

// 获取表单验证规则
function getValidator(fields) {
  let result = {};
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key];
    }
  }
  return result;
}

export default {
  data() {
    return {
      formData: {
        data_id: '',
        name: '',
        type: '基础分类',
        sort: 0
      },
      categoryTypes: [
        {
          value: '基础分类',
          text: '基础分类'
        },
        {
          value: '特殊分类',
          text: '特殊分类'
        }
      ],
      rules: {
        ...getValidator(['data_id', 'name', 'type', 'sort'])
      }
    };
  },
  onReady() {
    this.$refs.form.setRules(this.rules);
  },
  methods: {
    async submit() {
      try {
        // 表单验证
        await this.$refs.form.validate();

        // 检查分类 ID 是否重复
        const idCheckRes = await db.collection(dbCollectionName).where({
          data_id: this.formData.data_id
        }).get();
        if (Array.isArray(idCheckRes.data) && idCheckRes.data.length > 0) {
          uni.showToast({ title: '分类 ID 已存在，请重新输入', icon: 'none' });
          return;
        }

        // 确保 sort 字段为 number 类型
        this.formData.sort = Number(this.formData.sort);

        // 修改这里，将 Date 对象转换为时间戳
        this.formData.create_date = new Date().getTime();
        // 插入数据到数据库
        await db.collection(dbCollectionName).add(this.formData);

        // 触发更新分类事件
        uni.$emit('updateCategories');

        // 返回上一页
        uni.navigateBack();
      } catch (e) {
        // 显示错误信息
        uni.showToast({ title: e.message, icon: 'none' });
      }
    },
    cancel() {
      // 返回上一页
      uni.navigateBack();
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.form-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.button {
  width: 100px;
}
</style>